package com.yzs.exam.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * Rsa加密解密工具类
 * @author yzs
 * @create 2021-03-19 11:22
 */
public class RsaUtil {
    /**
     * 非对称密钥算法
     */
    private static final String ALGORITHM = "RSA";

    //字符编码集
    private static final String CHAR_SET = "utf-8";

    private static final Logger logger = LoggerFactory.getLogger(RsaUtil.class);

    public static String rsaEncode(String publicCertificate, String text) {
        try {
            //将公钥字符串解码为Base64的字节数据
            byte[] publicBytes = baseStrToByte(publicCertificate);
            //初始化公钥、密钥材料转换 -- 公钥编码方式对象 --代表公有密钥的ASN.1编码
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
            //实例化密钥工厂
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
            //产生公钥
            PublicKey pubKey = keyFactory.generatePublic(keySpec);
            //获取加密类对象（根据对应算法）
            final Cipher cipher = Cipher.getInstance(ALGORITHM);
            //初始化加密类：加密方式+公钥形式
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            //密码加密
            byte[] cipherBytes = cipher.doFinal(text.getBytes(CHAR_SET));
            //将加密后的密码编码为Base64字符串
            return baseByteToStr(cipherBytes);
        } catch (Exception e) {
            logger.error("publicCertificate:{}  \r\n  text:{}", publicCertificate, text, e);
        }
        return null;
    }


    public static String rsaDecode(String privateCertificate, String text) {
        try {
            //将私钥解码为base64字节数组
            byte[] privateBytes = baseStrToByte(privateCertificate);
            //获取私钥 -- 代表私有密钥的ASN.1编码
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateBytes);
            //实例化密钥工厂
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
            //产生私钥
            PrivateKey priKey = keyFactory.generatePrivate(keySpec);
            byte[] cipherText;
            // 初始化加密类
            final Cipher cipher = Cipher.getInstance(ALGORITHM);
            // 设置为私钥解码模式
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            //将密码通过解码器解码为字节数组
            byte[] textbyte = baseStrToByte(text);
            //对私钥进行解密
            cipherText = cipher.doFinal(textbyte);
            //返回私钥的解密后的字符串
            return new String(cipherText, CHAR_SET);
        } catch (Exception e) {
            logger.error("privateCertificate:{}  \r\n  text:{}", privateCertificate, text, e);
        }
        return null;
    }


    /**
     *
     * @param str str
     * @return byte[]
     */
    private static byte[] baseStrToByte(String str) {
        return Base64.getDecoder().decode(str);
    }


    /**
     * @param bytes bytes
     * @return String
     */
    private static String baseByteToStr(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }
}
